package com.wangwenjun.concurrency.chapter14.atomicreference;

import java.math.BigDecimal;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceExample3 {

    /**
     * BigDecimal is Immutable object
     * so if we want to change the value of BigDecimal, we can only do that:
     *
     * BigDecimal value = new BigDecimal("0");
     * value = value.add(new BigDecimal("1"));
     *
     * Note that wo can only make the new reference to the value object
     *
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100000);
        AtomicReference<BigDecimal> balance = new AtomicReference<>(new BigDecimal("0"));

        for (int i = 0; i < 100000; i++) {
            new Thread(()->{
                while (true){
                    if (balance.compareAndSet(balance.get(), balance.get().add(new BigDecimal("1")))) {
                        break;
                    }
                }
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();

        System.out.println(balance.get());

    }

}
